/*
 *    Copyright 2009-2025 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.parsing;

import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.ibatis.builder.BuilderException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * XPath解析器，用于解析XML文档并提供XPath查询功能 该类支持从字符串、Reader、InputStream或Document对象中创建XML文档，并提供各种XPath查询方法
 *
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XPathParser {

  private final Document document;
  private boolean validation;
  private EntityResolver entityResolver;
  private Properties variables;
  private XPath xpath;

  /**
   * 从XML字符串创建XPathParser实例
   *
   * @param xml
   *          XML字符串
   */
  public XPathParser(String xml) {
    commonConstructor(false, null, null);
    this.document = createDocument(new InputSource(new StringReader(xml)));
  }

  /**
   * 从Reader创建XPathParser实例
   *
   * @param reader
   *          包含XML数据的Reader
   */
  public XPathParser(Reader reader) {
    commonConstructor(false, null, null);
    this.document = createDocument(new InputSource(reader));
  }

  /**
   * 从InputStream创建XPathParser实例
   *
   * @param inputStream
   *          包含XML数据的InputStream
   */
  public XPathParser(InputStream inputStream) {
    commonConstructor(false, null, null);
    this.document = createDocument(new InputSource(inputStream));
  }

  /**
   * 直接使用Document对象创建XPathParser实例
   *
   * @param document
   *          已创建的Document对象
   */
  public XPathParser(Document document) {
    commonConstructor(false, null, null);
    this.document = document;
  }

  /**
   * 从XML字符串和验证标志创建XPathParser实例
   *
   * @param xml
   *          XML字符串
   * @param validation
   *          是否启用XML验证
   */
  public XPathParser(String xml, boolean validation) {
    commonConstructor(validation, null, null);
    this.document = createDocument(new InputSource(new StringReader(xml)));
  }

  /**
   * 从Reader和验证标志创建XPathParser实例
   *
   * @param reader
   *          包含XML数据的Reader
   * @param validation
   *          是否启用XML验证
   */
  public XPathParser(Reader reader, boolean validation) {
    commonConstructor(validation, null, null);
    this.document = createDocument(new InputSource(reader));
  }

  /**
   * 从InputStream和验证标志创建XPathParser实例
   *
   * @param inputStream
   *          包含XML数据的InputStream
   * @param validation
   *          是否启用XML验证
   */
  public XPathParser(InputStream inputStream, boolean validation) {
    commonConstructor(validation, null, null);
    this.document = createDocument(new InputSource(inputStream));
  }

  /**
   * 直接使用Document对象和验证标志创建XPathParser实例
   *
   * @param document
   *          已创建的Document对象
   * @param validation
   *          是否启用XML验证
   */
  public XPathParser(Document document, boolean validation) {
    commonConstructor(validation, null, null);
    this.document = document;
  }

  /**
   * 从XML字符串、验证标志和变量属性创建XPathParser实例
   *
   * @param xml
   *          XML字符串
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   */
  public XPathParser(String xml, boolean validation, Properties variables) {
    commonConstructor(validation, variables, null);
    this.document = createDocument(new InputSource(new StringReader(xml)));
  }

  /**
   * 从Reader、验证标志和变量属性创建XPathParser实例
   *
   * @param reader
   *          包含XML数据的Reader
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   */
  public XPathParser(Reader reader, boolean validation, Properties variables) {
    commonConstructor(validation, variables, null);
    this.document = createDocument(new InputSource(reader));
  }

  /**
   * 从InputStream、验证标志和变量属性创建XPathParser实例
   *
   * @param inputStream
   *          包含XML数据的InputStream
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   */
  public XPathParser(InputStream inputStream, boolean validation, Properties variables) {
    commonConstructor(validation, variables, null);
    this.document = createDocument(new InputSource(inputStream));
  }

  /**
   * 直接使用Document对象、验证标志和变量属性创建XPathParser实例
   *
   * @param document
   *          已创建的Document对象
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   */
  public XPathParser(Document document, boolean validation, Properties variables) {
    commonConstructor(validation, variables, null);
    this.document = document;
  }

  /**
   * 从XML字符串、验证标志、变量属性和EntityResolver创建XPathParser实例
   *
   * @param xml
   *          XML字符串
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   * @param entityResolver
   *          实体解析器
   */
  public XPathParser(String xml, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, variables, entityResolver);
    // 解析XML文档为Document对象
    this.document = createDocument(new InputSource(new StringReader(xml)));
  }

  /**
   * 从Reader、验证标志、变量属性和EntityResolver创建XPathParser实例
   *
   * @param reader
   *          包含XML数据的Reader
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   * @param entityResolver
   *          实体解析器
   */
  public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {

    commonConstructor(validation, variables, entityResolver);
    // 解析XML文档为Document对象
    this.document = createDocument(new InputSource(reader));
  }

  /**
   * 从InputStream、验证标志、变量属性和EntityResolver创建XPathParser实例
   *
   * @param inputStream
   *          包含XML数据的InputStream
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   * @param entityResolver
   *          实体解析器
   */
  public XPathParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, variables, entityResolver);
    this.document = createDocument(new InputSource(inputStream));
  }

  /**
   * 直接使用Document对象、验证标志、变量属性和EntityResolver创建XPathParser实例
   *
   * @param document
   *          已创建的Document对象
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          变量属性
   * @param entityResolver
   *          实体解析器
   */
  public XPathParser(Document document, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, variables, entityResolver);
    this.document = document;
  }

  /**
   * 设置变量属性
   *
   * @param variables
   *          变量属性
   */
  public void setVariables(Properties variables) {
    this.variables = variables;
  }

  /**
   * 评估XPath表达式并返回字符串结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 字符串结果
   */
  public String evalString(String expression) {
    return evalString(document, expression);
  }

  /**
   * 评估XPath表达式并返回字符串结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 字符串结果
   */
  public String evalString(Object root, String expression) {
    String result = (String) evaluate(expression, root, XPathConstants.STRING);
    return PropertyParser.parse(result, variables);
  }

  /**
   * 评估XPath表达式并返回布尔结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 布尔结果
   */
  public Boolean evalBoolean(String expression) {
    return evalBoolean(document, expression);
  }

  /**
   * 评估XPath表达式并返回布尔结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 布尔结果
   */
  public Boolean evalBoolean(Object root, String expression) {
    return (Boolean) evaluate(expression, root, XPathConstants.BOOLEAN);
  }

  /**
   * 评估XPath表达式并返回短整型结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 短整型结果
   */
  public Short evalShort(String expression) {
    return evalShort(document, expression);
  }

  /**
   * 评估XPath表达式并返回短整型结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 短整型结果
   */
  public Short evalShort(Object root, String expression) {
    return Short.valueOf(evalString(root, expression));
  }

  /**
   * 评估XPath表达式并返回整型结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 整型结果
   */
  public Integer evalInteger(String expression) {
    return evalInteger(document, expression);
  }

  /**
   * 评估XPath表达式并返回整型结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 整型结果
   */
  public Integer evalInteger(Object root, String expression) {
    return Integer.valueOf(evalString(root, expression));
  }

  /**
   * 评估XPath表达式并返回长整型结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 长整型结果
   */
  public Long evalLong(String expression) {
    return evalLong(document, expression);
  }

  /**
   * 评估XPath表达式并返回长整型结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 长整型结果
   */
  public Long evalLong(Object root, String expression) {
    return Long.valueOf(evalString(root, expression));
  }

  /**
   * 评估XPath表达式并返回浮点型结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 浮点型结果
   */
  public Float evalFloat(String expression) {
    return evalFloat(document, expression);
  }

  /**
   * 评估XPath表达式并返回浮点型结果
   *
   * @param root
   *          根对象
   * @param expression
   *          XPath表达式
   *
   * @return 浮点型结果
   */
  public Float evalFloat(Object root, String expression) {
    return Float.valueOf(evalString(root, expression));
  }

  /**
   * 评估XPath表达式并返回双精度浮点型结果
   *
   * @param expression
   *          XPath表达式
   *
   * @return 双精度浮点型结果
   */
  public Double evalDouble(String expression) {
    return evalDouble(document, expression);

  }

  /**
   * 评估XPath表达式并返回结果作为Double类型
   *
   * @param root
   *          XPath表达式的根对象
   * @param expression
   *          要评估的XPath表达式
   *
   * @return 表达式的评估结果，作为Double类型返回
   */
  public Double evalDouble(Object root, String expression) {
    return (Double) evaluate(expression, root, XPathConstants.NUMBER);
  }

  /**
   * 评估XPath表达式并返回结果作为XNode列表
   *
   * @param expression
   *          要评估的XPath表达式
   *
   * @return 表达式的评估结果，作为XNode列表返回
   */
  public List<XNode> evalNodes(String expression) {
    return evalNodes(document, expression);
  }

  /**
   * 评估XPath表达式并返回结果作为XNode列表
   *
   * @param root
   *          XPath表达式的根对象
   * @param expression
   *          要评估的XPath表达式
   *
   * @return 表达式的评估结果，作为XNode列表返回
   */
  public List<XNode> evalNodes(Object root, String expression) {
    List<XNode> xnodes = new ArrayList<>();
    NodeList nodes = (NodeList) evaluate(expression, root, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
      xnodes.add(new XNode(this, nodes.item(i), variables));
    }
    return xnodes;
  }

  /**
   * 评估XPath表达式并返回结果作为单个XNode
   *
   * @param expression
   *          要评估的XPath表达式
   *
   * @return 表达式的评估结果，作为单个XNode返回
   */
  public XNode evalNode(String expression) {
    // 根据XPATH语法，获取指定节点
    return evalNode(document, expression);
  }

  /**
   * 评估XPath表达式并返回结果作为单个XNode
   *
   * @param root
   *          XPath表达式的根对象
   * @param expression
   *          要评估的XPath表达式
   *
   * @return 表达式的评估结果，作为单个XNode返回
   */
  public XNode evalNode(Object root, String expression) {
    Node node = (Node) evaluate(expression, root, XPathConstants.NODE);
    if (node == null) {
      return null;
    }
    return new XNode(this, node, variables);
  }

  /**
   * 私有方法，用于评估XPath表达式
   *
   * @param expression
   *          要评估的XPath表达式
   * @param root
   *          XPath表达式的根对象
   * @param returnType
   *          期望的返回类型
   *
   * @return 表达式的评估结果
   *
   * @throws BuilderException
   *           如果评估过程中发生错误
   */
  private Object evaluate(String expression, Object root, QName returnType) {
    try {
      return xpath.evaluate(expression, root, returnType);
    } catch (Exception e) {
      throw new BuilderException("Error evaluating XPath.  Cause: " + e, e);
    }
  }

  /**
   * 创建XML文档实例
   *
   * @param inputSource
   *          XML输入源
   *
   * @return 解析后的XML文档实例
   *
   * @throws BuilderException
   *           如果文档创建过程中发生错误
   */
  private Document createDocument(InputSource inputSource) {
    // important: this must only be called AFTER common constructor
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      // 进行dtd或者Schema校验
      factory.setValidating(validation);

      factory.setNamespaceAware(false);
      // 设置忽略注释为true
      factory.setIgnoringComments(true);
      // 设置是否忽略元素内容中的空白
      factory.setIgnoringElementContentWhitespace(false);
      factory.setCoalescing(false);
      factory.setExpandEntityReferences(true);

      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setEntityResolver(entityResolver);
      builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void warning(SAXParseException exception) throws SAXException {
          // NOP
        }
      });
      // 通过dom解析，获取Document对象
      return builder.parse(inputSource);
    } catch (Exception e) {
      throw new BuilderException("Error creating document instance.  Cause: " + e, e);
    }
  }

  /**
   * 公用构造函数，初始化XPath处理器的共同资源
   *
   * @param validation
   *          是否启用XML验证
   * @param variables
   *          XPath变量
   * @param entityResolver
   *          实体解析器
   */
  private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
    this.validation = validation;
    this.entityResolver = entityResolver;
    this.variables = variables;
    XPathFactory factory = XPathFactory.newInstance();
    this.xpath = factory.newXPath();
  }
}
